<template>
  <div class="self_adaption">
    <div class="g-container">
      <div class="other">
        <p class="main_text">商城投诉</p>
      </div>

      <!-- 搜索 -->
      <div class="g-search" ref="searchBox">
        <!-- 时间选择区域 -->
        <div class="demo-date-picker">
          <div class="block">
            <span class="demonstration">提交时间：</span>
            <el-date-picker
              v-model="searchValue.startAt"
              type="date"
              placeholder="开始时间"
              @change="startTime"
              :clearable="false"
              :default-time="defaultTime(0, 0, 0)" />
            <span class="demonstration" style="display: inline-block; font-size: 12px; color: #898989; margin: 20px"
              >至</span
            >
            <el-date-picker
              v-model="searchValue.endAt"
              type="date"
              placeholder="结束时间"
              @change="endTime"
              :clearable="false"
              :default-time="defaultTime1(23, 59, 59)" />

            &emsp;
            <el-radio-group v-model="radio" class="ml-4" @change="radioSelect">
              <el-radio label="1" size="large">今天</el-radio>
              <el-radio label="2" size="large">昨天</el-radio>
              <el-radio label="3" size="large">近三天</el-radio>
              <el-radio label="4" size="large">近一周</el-radio>
              <el-radio label="5" size="large">近一个月</el-radio>
              <el-radio label="6" size="large">近三个月</el-radio>
              <el-radio label="7" size="large">近一年</el-radio>
            </el-radio-group>
          </div>
        </div>
        <!-- 信息区域 -->
        <div class="all_select">
          <!-- 投诉ID -->
          <div class="input_valye">
            <span class="demonstration">投诉编号：</span>
            <input
              type="number"
              class="input"
              placeholder="请输入投诉ID"
              v-model="searchValue.id"
              style="width: 200px"
              @keyup.enter="search" />
          </div>
          <!-- 投诉订单 -->
          <div class="input_valye">
            <span class="demonstration">投诉订单：</span>
            <input
              type="number"
              class="input"
              placeholder="请输入投诉订单"
              v-model="searchValue.orderSn"
              style="width: 200px"
              @keyup.enter="search" />
          </div>
          <!-- 处理状态 -->
          <div class="input_valye">
            <span class="demonstration">处理状态：</span>
            <el-select
              v-model="searchValue.status"
              class="m-2"
              placeholder="请选择处理状态"
              style="width: 200px"
              @change="search">
              <el-option v-for="item in riseType_options" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </div>
          <!-- 用户群体 -->
          <div class="input_valye">
            <span class="demonstration">用户群体：</span>
            <el-select
              v-model="searchValue.complaintType"
              class="m-2"
              placeholder="请选择用户群体"
              style="width: 200px"
              @change="search">
              <el-option v-for="item in user_options" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </div>
        </div>
        <!-- 底部按钮区域 -->
        <div class="bottom_btn">
          <el-button class="solid" @click="search">查询</el-button>
          <el-button class="hollow" @click="reset">重置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <div class="table">
        <!-- 表格导航栏 -->
        <div class="nav">
          <ul class="nav_ul">
            <li v-for="(item, index) in nav_list" :key="index" :class="item.class" @click="navChange(item)">
              <span class="nav_lis">{{ item.text }}</span>
            </li>
          </ul>
        </div>
        <!-- 表格区域 -->
        <el-table
          :data="tableData"
          style="width: 100%"
          :header-cell-style="{'text-align': 'center', background: '#F2F7FC !important'}"
          :show-overflow-tooltip="true">
          <el-table-column type="selection" width="40" />
          <el-table-column prop="id" label="投诉编号" align="center" />
          <el-table-column prop="orderSn" label="投诉订单" width="180" align="center">
            <template #default="item">
              <el-text tag="span" style="cursor: pointer" @click="Look(item.row)">{{ item.row.orderSn }}</el-text>
            </template>
          </el-table-column>
          <el-table-column prop="userId" label="提交群体" width="100" align="center">
            <template #default="item">
              <el-text v-if="item.row.complaintType == 0" class="mx-1" type="success">商家</el-text>
              <el-text v-else class="mx-1" type="primary">用户</el-text>
            </template>
          </el-table-column>
          <el-table-column prop="userId" label="提交用户名/用户名" min-width="200" align="center">
            <template #default="item">
              <span v-if="item.row.complaintType == 0">
                {{ item.row.shopName }}
              </span>
              <span v-else>
                {{ item.row.username }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="shopId" label="投诉对象ID" align="center" min-width="150">
            <template #default="item">
              <span v-if="item.row.complaintType == 0">
                {{ item.row.userId }}
              </span>
              <span v-else>
                {{ item.row.shopId }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="shopName" label="投诉店铺名/用户名" align="center" min-width="200">
            <template #default="item">
              <span v-if="item.row.complaintType == 0">
                {{ item.row.username }}
              </span>
              <span v-else>
                {{ item.row.shopName }}
              </span>
            </template></el-table-column
          >
          <el-table-column prop="reason" label="投诉原因" align="center" width="200" />
          <el-table-column prop="createdAt" label="提交时间" width="200" align="center" />
          <el-table-column prop="status" label="处理状态" width="120" align="center">
            <template #default="item">
              <el-text v-if="item.row.status == 0" class="mx-1" type="success">• 未处理</el-text>
              <el-text v-else-if="item.row.status == 1" class="mx-1" type="success">• 处理中</el-text>
              <el-text v-else class="mx-1" type="success">• 已完成</el-text>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" class="operation" :show-overflow-tooltip="false">
            <template #default="item">
              <div class="table_btn">
                <el-button size="small" class="none" @click="Look(item.row)">查看</el-button>
                <el-button size="small" class="none" @click="dispose(item.row.id)" v-if="item.row.status == 0"
                  >开始处理</el-button
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="note" label="备注" width="120" align="center" />
        </el-table>
        <!-- 分页器 -->
        <smartPager
          v-model:current-page="searchValue.page"
          v-model:page-size="searchValue.rows"
          :total="Number(total)"
          @change="pageChange"
          style="margin-left: 20px" />
      </div>
      <!-- 评价详情 -->
      <el-drawer v-model="mask" :with-header="false">
        <div class="title_pop">投诉单：</div>
        <div class="pop_topic">投诉内容</div>

        <div class="pop_content">
          <div class="con_text">用户ID：</div>
          <div class="con_right">{{ GoodsformDate.userId }}</div>
        </div>
        <div class="pop_content">
          <div class="con_text">用户名：</div>
          <div class="con_right">{{ GoodsformDate.username }}</div>
        </div>
        <div class="pop_content">
          <div class="con_text">投诉编号：</div>
          <div class="con_right">{{ GoodsformDate.compalintId }}</div>
        </div>
        <div class="pop_content">
          <div class="con_text">投诉订单：</div>
          <div class="con_right">{{ GoodsformDate.orderSn }}</div>
        </div>
        <div class="pop_content">
          <div class="con_text">提交时间：</div>
          <div class="con_right">{{ GoodsformDate.createdAt }}</div>
        </div>
        <div class="pop_content">
          <div class="con_text">投诉原因：</div>
          <div class="con_right">{{ GoodsformDate.reason }}</div>
        </div>
        <div class="pop_content">
          <div class="con_text">投诉说明：</div>
          <div class="con_right">{{ GoodsformDate.description }}</div>
        </div>
        <div style="margin: 10px 30px" v-if="GoodsformDate.dealImgs">
          <div v-if="GoodsformDate.dealImgs.length != 0">
            <el-image
              v-for="(item, index) in GoodsformDate.dealImgs"
              :key="index"
              :preview-src-list="[item]"
              :src="item"
              class="ph_b"
              style="width: 100px; height: 100px" />
          </div>
        </div>
        <div class="pop_topic">投诉处理</div>
        <el-form ref="ruleFormRef" :model="GoodsformDate" label-width="120px" label-position="top" :rules="rules">
          <el-form-item label="投诉结果" prop="result">
            <el-select
              v-model="GoodsformDate.result"
              class="m-2"
              placeholder="请选择处理状态"
              style="width: 100%"
              :disabled="GoodsformDate.status == '2'">
              <el-option v-for="item in result_options" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="投诉处理说明" prop="content">
            <el-input
              v-model="GoodsformDate.content"
              class="form_input"
              show-word-limit
              style="width: 100%"
              type="textarea"
              :rows="6"
              :disabled="GoodsformDate.status == '2'" />
          </el-form-item>

          <el-form-item v-if="GoodsformDate.status != '2'">
            <div class="photoBox">
              <el-upload
                action="#"
                list-type="picture-card"
                :auto-upload="false"
                v-model:file-list="GoodsformDate.dealImgs"
                :limit="3">
                <el-icon>
                  <Plus />
                </el-icon>
              </el-upload>
            </div>
          </el-form-item>
          <div v-else>
            <div v-if="GoodsformDate.dealImgs.length != 0">
              <el-image
                v-for="(item, index) in GoodsformDate.dealImgs"
                :src="item"
                :preview-src-list="[item]"
                :key="index"
                style="width: 120px; height: 120px" />
            </div>
          </div>
        </el-form>
        <div class="btn_center">
          <el-button class="hollow" @click="mask = !mask">取消</el-button>
          <el-button
            class="solid"
            @click="finishSure(ruleFormRef)"
            :loading="loading"
            v-if="GoodsformDate.status != '2'"
            >结束处理</el-button
          >
        </div>
      </el-drawer>
      <!-- 遮罩层 -->
      <div id="mask1" v-if="mask" @click="maskBtn1"></div>
    </div>
  </div>
</template>
<script setup lang="ts">
import {ref, onMounted, reactive, onBeforeUnmount} from 'vue';
import {UploadFilled} from '@element-plus/icons-vue';
import type {UploadInstance, UploadProps, UploadUserFile} from 'element-plus';
import {
  RequestComplaintGetlistlimit,
  RequestComplaintDeal,
  RequestComplaintGetDetail,
  RequestComplaintFinishDeal,
} from '@/api/path/index.js';
import type {FormInstance} from 'element-plus';
import {InfoFilled, Plus} from '@element-plus/icons-vue';
const ruleFormRef = ref<FormInstance>();
const uploadShow = ref(false); //上传发票显示
const mask = ref(false); //遮罩层显示
import moment from 'moment';
const radio = ref(''); //单选按钮
const showInvoice = ref(false); //控制组件显示
const total = ref(0); //发票总数
const tableData = ref([]); //发票数组
const sendMesChange = () => {
  GoodsformDate.value.sendMessage = !GoodsformDate.value.sendMessage;
};
// 表单规则
const rules = reactive({
  result: [{required: true, message: '请选择处理结果', trigger: 'blur'}],
  // unit: [{ required: true, message: '请选择商品单位', trigger: 'change' }],
  content: [{required: true, message: '请输入处理描述', trigger: 'blur'}],
});
const defaultTime = (H: any, M: any, S: any) => {
  var now = new Date();
  now.setHours(H);
  now.setMinutes(M);
  now.setSeconds(S);
  return now;
};
const defaultTime1 = (H: any, M: any, S: any) => {
  var now = new Date();
  now.setHours(H);
  now.setMinutes(M);
  now.setSeconds(S);
  return now;
};
onMounted(() => {
  requestComplaintGetlistlimit();
  handleResize();
  window.addEventListener('resize', handleResize);
});
const searchBox = ref();
const tablelistHeight = ref();
const handleResize = () => {
  const searchBoxHeight = searchBox.value.clientHeight;
  tablelistHeight.value = 110 + searchBoxHeight + 'px';
  console.log('Search Box height11111111111111111111111111111:', searchBoxHeight);
};

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);
});
const nav_list = ref([
  {
    class: ['navlist', 'nav_li'],
    text: '全部',
    status: '',
    num: 0,
  },
  {
    class: ['nav_li'],
    text: '待处理',
    status: 0,
    num: 0,
  },
  {
    class: ['nav_li'],
    text: '处理中',
    status: 1,
    num: 0,
  },
  {
    class: ['nav_li'],
    text: '已完成',
    status: 2,
    num: 0,
  },
]);
const GoodsformDate = ref({
  description: '',
  reason: '',
  createdAt: '',
  orderSn: '',
  username: '',
  userId: '',
  compalintId: '',
  auditAdmin: '',
  content: '',
  sendMessage: true,
  result: '',
  dealImgs: [],
  status: '',
});
/**
 * 处理类型
 */
const riseType_options = [
  {
    value: 0,
    label: '未处理',
  },
  {
    value: 1,
    label: '处理中',
  },
  {
    value: 2,
    label: '已完成',
  },
];

/**
 * 用户群体
 */
const user_options = [
  {
    value: '0',
    label: '商家',
  },
  {
    value: '1',
    label: '用户',
  },
];
/**
 * 处理结果
 */
const result_options = [
  {
    value: '封号',
    label: '封号',
  },
  {
    value: '警告',
    label: '警告',
  },
  {
    value: '扣除信誉分',
    label: '扣除信誉分',
  },
];
/**
 * 获取投诉
 */
const requestComplaintGetlistlimit = async () => {
  const a = await RequestComplaintGetlistlimit(searchValue.value);
  console.log('获取成功', a.resultObj);
  tableData.value = a.resultObj.list;
  total.value = a.resultObj.count;
};
/**
 * 表格导航栏点击切换
 */
const navChange = (item: any) => {
  for (let i = 0; i < nav_list.value.length; i++) {
    const filteredClasses = nav_list.value[i].class.filter((className) => className !== 'navlist');
    nav_list.value[i].class = filteredClasses;
  }
  item.class.push('navlist');
  searchValue.value.status = item.status;
  searchValue.value.page = 1;
  requestComplaintGetlistlimit();
};
/**
 * 分页
 */
const pageChange = async (val: number) => {
  requestComplaintGetlistlimit();
};
/**
 * 时间范围单选按钮
 */
const radioSelect = () => {
  searchValue.value.startAt = '';
  searchValue.value.endAt = '';
  var now = new Date();
  now.setHours(0);
  now.setMinutes(0);
  now.setSeconds(0);
  var now1 = new Date();
  now1.setHours(23);
  now1.setMinutes(59);
  now1.setSeconds(59);
  if (radio.value === '1') {
    searchValue.value.startAt = moment(now).format('YYYY-MM-DD HH:mm:ss');
    searchValue.value.endAt = moment(now1).format('YYYY-MM-DD HH:mm:ss');
  } else if (radio.value === '2') {
    searchValue.value.startAt = moment(now).subtract(1, 'days').format('YYYY-MM-DD HH:mm:ss');
    searchValue.value.endAt = moment(now1).subtract(1, 'days').format('YYYY-MM-DD HH:mm:ss');
  } else if (radio.value === '3') {
    searchValue.value.startAt = moment(now).subtract(3, 'days').format('YYYY-MM-DD HH:mm:ss');
    searchValue.value.endAt = moment(now1).format('YYYY-MM-DD HH:mm:ss');
  } else if (radio.value === '4') {
    searchValue.value.startAt = moment(now).subtract(7, 'days').format('YYYY-MM-DD HH:mm:ss');
    searchValue.value.endAt = moment(now1).format('YYYY-MM-DD HH:mm:ss');
  } else if (radio.value === '5') {
    searchValue.value.startAt = moment(now).subtract(1, 'months').format('YYYY-MM-DD HH:mm:ss');
    searchValue.value.endAt = moment(now1).format('YYYY-MM-DD HH:mm:ss');
  } else if (radio.value === '6') {
    searchValue.value.startAt = moment(now).subtract(3, 'months').format('YYYY-MM-DD HH:mm:ss');
    searchValue.value.endAt = moment(now1).format('YYYY-MM-DD HH:mm:ss');
  } else {
    searchValue.value.startAt = moment(now).subtract(1, 'years').format('YYYY-MM-DD HH:mm:ss');
    searchValue.value.endAt = moment(now1).format('YYYY-MM-DD HH:mm:ss');
  }
  search();
};
/**
 * 搜索值
 */
const searchValue = ref({
  startAt: '',
  endAt: '',
  orderSn: '',
  complaintType: '',
  id: null,
  status: '',
  page: 1,
  rows: 10,
});
/**
 * 点击重置
 */
const reset = () => {
  searchValue.value = {
    startAt: '',
    endAt: '',
    orderSn: '',
    complaintType: '',
    id: null,
    status: '',
    page: 1,
    rows: 10,
  };
  radio.value = '';
  requestComplaintGetlistlimit();
};
// 开始时间
const startTime = () => {
  searchValue.value.startAt.setHours(0);
  searchValue.value.startAt.setMinutes(0);
  searchValue.value.startAt.setSeconds(0);
  searchValue.value.startAt = moment(searchValue.value.startAt).format('yyyy-MM-DD HH:mm:ss');
  radio.value = '';
  search();
};
// 结束时间
const endTime = () => {
  searchValue.value.endAt.setHours(23);
  searchValue.value.endAt.setMinutes(59);
  searchValue.value.endAt.setSeconds(59);
  searchValue.value.endAt = moment(searchValue.value.endAt).format('yyyy-MM-DD HH:mm:ss');
  radio.value = '';
  search();
};
/**
 * 搜索点击事件
 */
const search = async () => {
  if (moment(searchValue.value.startAt).diff(moment().format('YYYY-MM-DD HH:mm:ss')) >= 0) {
    ElMessage.error('开始时间不能晚于当前日期');
    searchValue.value.startAt = '';
  } else {
    if (searchValue.value.startAt !== '' && searchValue.value.endAt !== '') {
      if (moment(searchValue.value.startAt).diff(moment(searchValue.value.endAt)) <= 0) {
        searchValue.value.page = 1;
        requestComplaintGetlistlimit();
      } else {
        ElMessage.error('结束时间不能早于开始时间');
        searchValue.value.endAt = '';
      }
    } else {
      searchValue.value.page = 1;
      requestComplaintGetlistlimit();
    }
  }
};
/**
 * 点击查看
 */
const Look = async (item: any) => {
  const a = await RequestComplaintGetDetail(item.id);
  mask.value = true;
  GoodsformDate.value = {
    description: item.description,
    reason: item.reason,
    createdAt: item.createdAt,
    orderSn: item.orderSn,
    username: item.username,
    userId: item.userId,
    compalintId: item.id,
    auditAdmin: a.resultObj.complaintLog.auditAdmin,
    content: a.resultObj.complaintLog.content,
    sendMessage: a.resultObj.complaintLog.sendMessage,
    result: a.resultObj.complaintLog.result,
    dealImgs: a.resultObj.complaintLog.dealImgs,
    status: item.status,
  };
  if (GoodsformDate.value.sendMessage == null) {
    GoodsformDate.value.sendMessage = false;
  }
  if (GoodsformDate.value.dealImgs == null) {
    GoodsformDate.value.dealImgs = [];
  }
  console.log('查看', GoodsformDate.value);
};
/**
 * 点击结束
 */
const finish = (item: any) => {
  console.log(1111111111);
};
/**
 * 开始处理
 */
const dispose = async (id: number) => {
  const a = await RequestComplaintDeal(id);
  if (a.msg == '操作成功！') {
    ElMessage.success('操作成功');
    requestComplaintGetlistlimit();
  } else {
    ElMessage.error('操作失败！请重试');
  }
};

const fileList = ref<any>([]);
/**
 * 点击处理结束
 */

let loading = ref(false); //设置记录时间，用于防抖
let timer = ref(null); //设置记录时间，用于防抖
const finishSure = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async (valid: any, fields: any) => {
    if (valid) {
      if (timer != null) {
        clearTimeout(timer);
      }
      timer = setTimeout(async () => {
        loading.value = true;
        fileList.value = [];
        for (let i = 0; i < GoodsformDate.value.dealImgs.length; i++) {
          fileList.value[i] = await FileToBase64(GoodsformDate.value.dealImgs[i].raw);
          if (i == GoodsformDate.value.dealImgs.length - 1) {
            console.log('投诉信息', {
              compalintId: GoodsformDate.value.compalintId,
              auditAdmin: JSON.parse(localStorage.getItem('roleInfo')).id,
              content: GoodsformDate.value.content,
              sendMessage: GoodsformDate.value.sendMessage,
              result: GoodsformDate.value.result,
              dealImgs: fileList.value,
            });
            const result = await RequestComplaintFinishDeal({
              compalintId: GoodsformDate.value.compalintId,
              auditAdmin: JSON.parse(localStorage.getItem('roleInfo')).id,
              content: GoodsformDate.value.content,
              sendMessage: GoodsformDate.value.sendMessage,
              result: GoodsformDate.value.result,
              dealImgs: fileList.value,
            });
            if (result.msg == '操作成功！') {
              ElMessage.success('处理成功！');
              requestComplaintGetlistlimit();
              maskBtn1();
            } else {
              ElMessage.error('处理失败！请重试');
            }
          }
        }
      }, 500);
    }
  });
};
const FileToBase64 = (file) => {
  return new Promise((resolve, reject) => {
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = async function (e) {
      resolve(e.target!.result);
    };
  });
};
/**
 * 遮罩层数据
 */
const maskBtn1 = () => {
  mask.value = false;
  showInvoice.value = false;
  uploadShow.value = false;
};
</script>
<style lang="scss" scoped>
@import '@/assets/css/plateform/Article/Content.css';
@import '@/assets/css/plateform/Shop/GoodsManage.css';

::v-deep .el-upload-dragger {
  width: 100% !important;
}

.nav_ul {
  width: 100%;

  .nav_li {
    width: 100px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .nav_lis {
    position: relative;
    cursor: pointer;

    .number {
      padding: 0 5px;
      display: block;
      line-height: 16px;
      height: 16px;
      color: #fff;
      font-size: 12px;
      background: #409eff;
      border-radius: 8px;
      position: absolute;
      top: 2px;
      right: -12px;
    }
  }

  .navlist {
    .number {
      background: #116cf8;
      color: #fff;
    }
  }
}

.look_invoice {
  width: 50%;
  height: 60%;
  position: fixed;
  top: 20%;
  left: 25%;
  z-index: 99;
  background: #fff;

  .content1 {
    height: calc(100% - 5.625rem);
  }
}

.look_invoice1 {
  width: 500px;
  height: 400px;
  position: fixed;
  top: 50%;
  left: 50%;
  margin-top: -200px;
  margin-left: -250px;
  z-index: 99;
  background: #fff;
}

.el-table .check_table {
  background: pink !important;
}

.table {
  height: calc(100% - v-bind(tablelistHeight)) !important;
}

::v-deep .el-table--fit {
  height: calc(100% - 100px) !important;
}

.table :deep(.el-table__cell) {
  text-align: center;
}

.el-form-item :deep(.el-input-group__prepend) {
  width: 10px;
  background-color: #116cf8;
  color: #fff;
}

.el-table .warning-row {
  background: #f2f7fc;
}

.title_pop {
  font-weight: 700;
  font-size: 18px;
  color: #303133;
  line-height: 26px;
}

.pop_topic {
  height: 40px;
  background: #f5f7fa;
  font-size: 16px;
  color: #1d2129;
  line-height: 40px;
  margin-top: 28px;
  font-weight: normal;
  padding: 0 8px;
}

.pop_content {
  display: flex;
  align-items: center;
  margin-top: 16px;
  font-size: 14px;
  color: #333;
  flex-wrap: wrap;

  .con_text {
    width: 100px;
    text-align: right;
    color: #b2b2b2;
  }
}

:deep(.el-drawer.rtl) {
  background: #fff;
  width: 600px !important;
}

// ::v-deep
//   .el-form--default.el-form--label-top
//   .el-form-item
//   .el-form-item__label {
//   margin: 8px auto !important;
// }
</style>
